<template>
  <div class="modal-overlay" @click.self="closeModal">
    <div class="modal-content">
      <!-- 关闭按钮 -->
      <button class="close-button" @click="closeModal">
        ×
      </button>
      
      <div class="anime-detail-container">
        <!-- 动漫封面 -->
        <div class="anime-cover">
          <CustomImage 
            :src="anime.coverImageUrl" 
            :alt="anime.title"
            customClass="cover-image"
            @error="setDefaultImage"
          />
        </div>
        
        <!-- 动漫信息 -->
        <div class="anime-details">
          <h2 class="anime-title">{{ anime.title }}</h2>
          <h3 class="anime-original-title" v-if="anime.originalTitle && anime.originalTitle !== anime.title">{{ anime.originalTitle }}</h3>
          
          <div class="anime-meta">
            <div class="rating">
              <span class="rating-icon">★</span>
              <span class="rating-value">{{ anime.rating || '暂无评分' }}</span>
            </div>
            
            <div class="votes">
              <span class="votes-icon">👍</span>
              <span class="votes-value">{{ anime.votes || 0 }}票</span>
            </div>
            
            <div class="favorites">
              <span class="favorites-icon">★</span>
              <span class="favorites-value">{{ favoritesCount || 0 }}收藏</span>
            </div>
          </div>
          
          <!-- 动漫描述 -->
          <div class="anime-description">
            <h3>剧情简介</h3>
            <p>{{ anime.synopsis || anime.description || '暂无剧情简介' }}</p>
          </div>
          
          <!-- 动漫详细信息 -->
          <div class="anime-detail-grid">
            <div class="detail-item">
              <span class="detail-label">年份</span>
              <span class="detail-value">{{ anime.year || '未知' }}</span>
            </div>
            
            <div class="detail-item">
              <span class="detail-label">季度</span>
              <span class="detail-value">{{ anime.season || '未知' }}</span>
            </div>
            
            <div class="detail-item">
              <span class="detail-label">类型</span>
              <span class="detail-value">{{ anime.genre || '未知' }}</span>
            </div>
            
            <div class="detail-item">
              <span class="detail-label">导演/演员</span>
              <span class="detail-value">{{ anime.director || '未知' }}</span>
            </div>
            
            <div class="detail-item">
              <span class="detail-label">集数</span>
              <span class="detail-value">{{ anime.episodes || '未知' }}集</span>
            </div>
            
            <div class="detail-item">
              <span class="detail-label">工作室</span>
              <span class="detail-value">{{ anime.studio || '未知' }}</span>
            </div>
          </div>
          
          <!-- 操作按钮 -->
          <div class="action-buttons">
            <!-- 使用全局VoteButton组件 -->
            <VoteButton 
              :anime-id="anime.id"
              @vote="onVote($event)"
            />
            
            <button 
              class="favorite-button"
              :class="{ 'favorited': isFavorited }"
              :disabled="isFavoriting"
              @click="handleFavorite"
            >
              <span v-if="isFavoriting">收藏中...</span>
              <span v-else-if="isFavorited">已收藏</span>
              <span v-else>收藏</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { Anime } from '../types/anime'
import { GLOBAL_CONFIG } from '../config'
import { checkFavorite, getAnimeFavoriteCount } from '../services/favoriteService'
import CustomImage from './common/CustomImage.vue'

// 定义组件的属性
const props = defineProps<{
  anime: Anime
}>()

// 定义组件的事件
const emit = defineEmits<{
  close: []
  vote: [animeId: number]
  favorite: [eventData: number | { animeId: number, isFavorited: boolean }]
}>()

// 组件内部状态
const isFavorited = ref(false)
const isFavoriting = ref(false)
const favoritesCount = ref(0)

// 移除了处理图片URL的计算属性，因为CustomImage组件会自动处理

// 检查用户是否已收藏
const checkFavoriteStatus = async () => {
  try {
    // 优先使用传入的isFavorite属性（如果有）
    if (props.anime.isFavorite !== undefined) {
      isFavorited.value = props.anime.isFavorite
    } else {
      // 否则单独检查
      const animeId = typeof props.anime.id === 'string' ? parseInt(props.anime.id) : props.anime.id
      const isFavorite = await checkFavorite(animeId)
      isFavorited.value = isFavorite
    }
    
    // 获取收藏数量 - 优先使用传入的favorites属性
    if (props.anime.favorites !== undefined) {
      favoritesCount.value = props.anime.favorites
    } else {
      const animeId = typeof props.anime.id === 'string' ? parseInt(props.anime.id) : props.anime.id
      const count = await getAnimeFavoriteCount(animeId)
      favoritesCount.value = count
    }
  } catch (error) {
    console.error('获取收藏状态失败:', error)
    // 失败时使用本地存储的备用方案
    const favorites = localStorage.getItem('favorites')
    if (favorites) {
      const favoriteIds = JSON.parse(favorites) as Array<string | number>
      const idAsString = props.anime.id.toString()
      isFavorited.value = favoriteIds.includes(props.anime.id) || favoriteIds.includes(idAsString)
    }
    
    // 使用传入的收藏数量
    favoritesCount.value = props.anime.favorites || 0
  }
}

// 关闭模态框
const closeModal = () => {
  emit('close')
}

// 处理图片加载失败，设置默认图片
  const setDefaultImage = (event?: Event) => {
    if (event) {
      const target = event.target as HTMLImageElement
      target.src = GLOBAL_CONFIG.DEFAULT_IMAGE_PATH
    }
  }

// 导入VoteButton组件
import VoteButton from './common/VoteButton.vue';
import toastService from '../services/toastService';

// 处理投票事件
const onVote = (animeId: number) => {
  // 直接触发投票事件给父组件，由父组件统一处理API调用
  emit('vote', animeId)
}

// 处理收藏
const handleFavorite = async () => {
  // 检查用户是否已登录
  const user = localStorage.getItem('user')
  if (!user) {
    // 显示登录提示
    if ((window as any).showLoginModal) {
      (window as any).showLoginModal('请先登录后再收藏！')
    } else {
      toastService.info('请先登录后再收藏！')
    }
    return
  }
  
  if (isFavoriting.value) return
  
  // 开始收藏过程
  isFavoriting.value = true
  
  try {
    // 保存操作前的收藏状态
    const wasFavorited = isFavorited.value
    
    // 触发收藏事件，API调用和数据处理由父组件负责
    // 这样可以避免子组件和父组件重复调用API
    emit('favorite', {
      animeId: props.anime.id,
      isFavorited: wasFavorited
    })
    
    // 直接乐观更新UI状态
    isFavorited.value = !wasFavorited
    favoritesCount.value = wasFavorited 
      ? Math.max(0, favoritesCount.value - 1) 
      : favoritesCount.value + 1
    
  } catch (error) {
    console.error('收藏操作失败:', error)
    // 如果操作失败，可以考虑重新检查真实的收藏状态
    try {
      const animeId = typeof props.anime.id === 'string' ? parseInt(props.anime.id) : props.anime.id
      isFavorited.value = await checkFavorite(animeId)
      favoritesCount.value = await getAnimeFavoriteCount(animeId)
    } catch (retryError) {
      console.error('重新检查收藏状态失败:', retryError)
    }
  } finally {
    isFavoriting.value = false
  }
}

// 组件挂载时检查收藏状态
  onMounted(async () => {
    await checkFavoriteStatus()
  })
</script>

<style scoped>
/* 模态框遮罩层 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 16px;
}

/* 模态框内容 */
.modal-content {
  background-color: white;
  border-radius: 20px;
  box-shadow: 0 10px 50px rgba(0, 0, 0, 0.3);
  max-width: 900px;
  width: 100%;
  max-height: 80vh;
  overflow-y: auto;
  position: relative;
  padding: 24px;
}

/* 关闭按钮 */
.close-button {
  position: absolute;
  top: 16px;
  right: 16px;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #F2F2F7;
  color: #8E8E93;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.close-button:hover {
  background-color: #E5E5EA;
  color: #1C1C1E;
}

/* 动漫详情容器 */
.anime-detail-container {
  display: flex;
  gap: 32px;
  margin-top: 24px;
}

/* 动漫封面 */
.anime-cover {
  flex-shrink: 0;
  width: 240px;
}

.cover-image {
  width: 100%;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

/* 动漫信息 */
.anime-details {
  flex: 1;
  min-width: 0;
}

.anime-title {
  font-size: 1.75rem;
  font-weight: 700;
  color: #1C1C1E;
  margin-bottom: 8px;
  line-height: 1.2;
}

.anime-original-title {
  font-size: 1.25rem;
  font-weight: 500;
  color: #6C6C70;
  margin-bottom: 16px;
  line-height: 1.2;
}

/* 动漫元数据 */
.anime-meta {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #E5E5EA;
}

.rating, .votes, .favorites {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
}

.rating {
  color: #FFD700;
}

.votes {
  color: #6C6C70;
}

.favorites {
  color: #FF69B4;
}

/* 动漫描述 */
.anime-description {
  margin-bottom: 24px;
}

.anime-description h3 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1C1C1E;
  margin-bottom: 12px;
}

.anime-description p {
  color: #6C6C70;
  line-height: 1.6;
}

/* 动漫详细信息网格 */
.anime-detail-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #E5E5EA;
}

.detail-item {
  display: flex;
  flex-direction: column;
}

.detail-label {
  font-size: 0.875rem;
  color: #8E8E93;
  margin-bottom: 4px;
}

.detail-value {
  font-size: 1rem;
  color: #1C1C1E;
  font-weight: 500;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 16px;
}

.vote-button, .favorite-button {
  flex: 1;
  padding: 12px 24px;
  border: none;
  border-radius: 12px;
  font-weight: 600;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.vote-button {
  background-color: #FF69B4;
  color: white;
}

.vote-button:hover:not(:disabled) {
  background-color: #FF1493;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 105, 180, 0.3);
}

.vote-button.voted {
  background-color: #34C759;
}

.vote-button.voted:hover:not(:disabled) {
  background-color: #30B053;
}

.favorite-button {
  background-color: #F2F2F7;
  color: #1C1C1E;
  border: 2px solid #FF69B4;
}

.favorite-button:hover:not(:disabled) {
  background-color: #FFE6F2;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 105, 180, 0.2);
}

.favorite-button.favorited {
  background-color: #FF69B4;
  color: white;
}

.favorite-button.favorited:hover:not(:disabled) {
  background-color: #FF1493;
}

.vote-button:disabled, .favorite-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .anime-detail-container {
    flex-direction: column;
    gap: 24px;
  }
  
  .anime-cover {
    width: 180px;
    margin: 0 auto;
  }
  
  .anime-title {
    text-align: center;
    font-size: 1.5rem;
  }
  
  .anime-meta {
    justify-content: center;
  }
  
  .anime-detail-grid {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}

@media (max-width: 480px) {
  .modal-content {
    padding: 16px;
    margin: 8px;
  }
  
  .anime-cover {
    width: 150px;
  }
  
  .anime-title {
    font-size: 1.25rem;
  }
  
  .anime-meta {
    flex-wrap: wrap;
    gap: 16px;
    justify-content: center;
  }
}
</style>